<template>
	<el-dialog v-model="dialogVisible" append-to-body :show-close="false" :close-on-click-modal="false"
		class="flex-align" style="width: 100%;height: 100%;padding: 30px 24px;margin: 0;background: transparent;">
		<template #header>
			<el-card style="width: 100%;height: 100%;" body-style="padding: 0;" shadow="never">
				<template #header>
					<div class="flex-space-between">
						<div>
							<el-text style="font-size: 16px;">
								退货明细
							</el-text>
						</div>
						<div>
							<el-button @click="closeDialog">取消</el-button>
							<!-- <el-button @click="closeDialog">
								保存并继续创建
								<el-icon style="margin-left: 4px;">
									<ArrowDown />
								</el-icon>
							</el-button> -->
							<el-button type="primary" @click="submitForm(vFormRef)">
								保存
							</el-button>
						</div>
					</div>
				</template>
				<el-scrollbar :style="`height: calc(100vh - 69px - ( 30px + 30px));`">
					<el-form :model="formData" :rules="rules" ref="vFormRef" label-position="top" label-width="50px"
						style="padding: 16px;">
						<el-form-item label="退货单" prop="order">
							<el-select @clear="selectClear('order')" v-model="formData.order"
								@change="(value:any)=>selectChange(value,'order')" multiple ref="order" clearable>
								<el-option v-for="item in orderOption" :key="key" :label="item?.label"
									:value="item?.value">
									<!--  -->
									<div class="flex-align-center">
										<el-icon :color="item?.color">
											<component :is="item?.icon"></component>
										</el-icon>
										<!--  -->
										<el-text style="margin-left: 6px;">{{item?.label}}</el-text>
									</div>
								</el-option>
								<!--  -->
								<template #tag>
									<div class="flex-align-center">
										<el-icon :color="orderOption[orderIndex]?.color">
											<component :is="orderOption[orderIndex]?.icon">
											</component>
										</el-icon>
										<!--  -->
										<el-text size="small"
											style="margin-left: 6px;">{{orderOption[orderIndex]?.label}}</el-text>
									</div>
								</template>
							</el-select>
						</el-form-item>
						<el-form-item label="退货产品" prop="product">
							<el-select @clear="selectClear('product')" v-model="formData.product"
								@change="(value:any)=>selectChange(value,'product')" multiple ref="product" clearable>
								<el-option v-for="item in productOption" :key="key" :label="item?.label"
									:value="item?.value">
									<!--  -->
									<div class="flex-align-center">
										<el-icon :color="item?.color">
											<component :is="item?.icon"></component>
										</el-icon>
										<!--  -->
										<el-text style="margin-left: 6px;">{{item?.label}}</el-text>
									</div>
								</el-option>
								<!--  -->
								<template #tag>
									<div class="flex-align-center">
										<el-icon :color="productOption[productIndex]?.color">
											<component :is="productOption[productIndex]?.icon">
											</component>
										</el-icon>
										<!--  -->
										<el-text size="small"
											style="margin-left: 6px;">{{productOption[productIndex]?.label}}</el-text>
									</div>
								</template>
							</el-select>
						</el-form-item>
						<el-form-item label="本次退货数量" prop="quantityShipped">
							<el-input type="number" v-model="formData.quantityShipped" clearable></el-input>
						</el-form-item>
						<el-form-item label="退货单价" prop="returnPrice">
							<el-input type="number" v-model="formData.returnPrice" clearable></el-input>
						</el-form-item>
						<el-form-item label="退货订单明细" prop="orderDetail">
							<el-select disabled placeholder="请选择:退货产品" @clear="selectClear('product')"
								v-model="formData.orderDetail" @change="(value:any)=>selectChange(value,'product')"
								multiple ref="orderDetail" clearable>
								<el-option v-for="item in orderDetailOption" :key="key" :label="item?.label"
									:value="item?.value">
									<!--  -->
									<div class="flex-align-center">
										<el-icon :color="item?.color">
											<component :is="item?.icon"></component>
										</el-icon>
										<!--  -->
										<el-text style="margin-left: 6px;">{{item?.label}}</el-text>
									</div>
								</el-option>
								<!--  -->
								<template #tag>
									<div class="flex-align-center">
										<el-icon :color="orderDetailOption[orderDetailIndex]?.color">
											<component :is="orderDetailOption[orderDetailIndex]?.icon">
											</component>
										</el-icon>
										<!--  -->
										<el-text size="small"
											style="margin-left: 6px;">{{orderDetailOption[orderDetailIndex]?.label}}</el-text>
									</div>
								</template>
							</el-select>
						</el-form-item>
						<el-form-item label="应退款金额" prop="refundAmount">
							<el-input type="text" disabled placeholder="保存后显示计算结果" v-model="formData.refundAmount"
								clearable></el-input>
						</el-form-item>
					</el-form>
				</el-scrollbar>
				<!--  -->
			</el-card>
		</template>
	</el-dialog>
</template>

<script setup lang="ts">
	import { reactive, ref } from 'vue';
	import { useRoute, useRouter } from 'vue-router';
	import request from '../../../utils/request';
	import { UserFilled, WalletFilled, CirclePlus, DocumentAdd, Delete } from '@element-plus/icons-vue';
	import { mergeObjects, formatNumber } from '../../../utils';
	import { useSelect } from '../../../utils/mixins';
	import { ElMessage, FormInstance } from 'element-plus';
	const emits = defineEmits(['update']);
	const { handSelectChange } = useSelect();
	const router = useRouter();
	const route = useRoute();
	const vFormRef = ref(null);
	const loading = ref(false);

	// 表单
	const formData = ref({
		order: [],
		orderId: null,
		product: [],
		productId: [],
		quantityShipped: null,
		returnPrice: null,
		orderDetail: [],
		orderDetailId: null,
		refundAmount: null,
	});
	//验证
	const rules = reactive({
		order: [{ required: true, message: '退货单必选！', trigger: ['blur', 'change'] }],
		product: [{ required: true, message: '退货产品必选！', trigger: ['blur', 'change'] }],
		quantityShipped: [{ required: true, message: '退货数量必填！', trigger: ['blur', 'change'] }],
		returnPrice: [{ required: true, message: '退货单价必填！', trigger: ['blur', 'change'] }],
		orderDetail: [{ required: true, message: '退货明细必选！', trigger: ['blur', 'change'] }],
		refundAmount: [],
	});
	const pageData = ref({
		pageNum: 1,
		pageSize: 1000,
		total: 0,
		pages: 0,
	});
	//退货订单
	const orderOption = ref([]);
	const orderIndex = ref(-1);
	const order = ref(null);
	//退货订单明细
	const orderDetailOption = ref([]);
	const orderDetailIndex = ref(-1);
	const orderDetail = ref(null);
	//退货产品
	const productOption = ref([]);
	const productIndex = ref([]);
	const product = ref(null);
	//
	const dialogVisible = ref(false);
	/**
	 * 打开弹出层
	 */
	const openDialog = () => {
		dialogVisible.value = true;
		setTimeout(async () => {
			const result = await getPageId();
			//
			if (result) {
				getSalesReturnList();
			}
		}, 10);
	}
	/**
	 * 关闭弹出层
	 */
	const closeDialog = () => {
		dialogVisible.value = false;
		vFormRef.value.resetFields();
		//清空url参数
		router.push({ query: {} });
	}
	//获取当前页面的数据
	const getPageId = async () => {
		if (!route.query.id) {
			return true;
		}
		const result = await request({
			url: '/login/selectSalesReturnById',
			params: {
				id: route.query.id
			},
		});
		//
		console.log('getPageId --->', result);
		formData.value = { ...result.data.t };
		return true;
	}
	const selectClear = (type : string) => {
		formData.value[type] = [];
	}
	//改变
	const selectChange = (value : Array<any>, type : string, key : number) => {
		//所有下拉框的配置列表
		const typeList = [{
			type: 'order', //哪一个下拉框，根据ref
			option: orderOption, //下拉列表选项
			indexVar: orderIndex, //当前选中项
			idVar: 'orderId', //当前id值
			blurRef: order, //ref
		}, {
			type: 'orderDetail', //哪一个下拉框，根据ref
			option: orderDetailOption, //下拉列表选项
			indexVar: orderDetailIndex, //当前选中项
			idVar: 'orderDetailId', //当前id值
			blurRef: orderDetail, //ref
		}, {
			type: 'product', //哪一个下拉框，根据ref
			option: productOption, //下拉列表选项
			indexVar: productIndex, //当前选中项
			idVar: 'productId', //当前id值
			blurRef: product, //ref
		},];
		//
		handSelectChange(formData, typeList, value, type, key);
	}
	//获取所有退货单
	const getSalesReturnList = async () => {
		const result = await request({
			url: '/login/selectSalesReturnAll',
			params: pageData.value,
		});
		//
		console.log('getPageList --->', result);
		orderOption.value = [];
		result.data.t.list.forEach((item : any, key : number) => {
			orderOption.value.push({
				label: `${item.salesOrder.orderNumber}_${item.customer.customerName}
				(${item.customer.customerRating})`,
				value: item.returnId,
				icon: WalletFilled,
				color: '#82b51b'
			});
			if (formData.value.orderId === item.returnId) {
				formData.value.order = [item.returnId];
				orderIndex.value = key;
			}
		});
	}
	//提交表单
	const submitForm = async (formEl : FormInstance | undefined) => {
		if (!formEl) return;
		await formEl.validate(async (valid, fields) => {
			if (valid) {
				console.log('submitForm ---> ', formData.value);
				const data = { ...formData.value };
				delete data.order;
				let type = '';
				if (!route.query.id) {
					type = '/saveSalesReturn';
				} else {
					type = '/updateSalesReturn';
				}
				//
				const result = await request({
					url: '/login' + type,
					data: data,
					method: 'post'
				});
				//
				console.log('submitForm--->', result);
				//
				if (result.data.code === 200) {
					ElMessage.success({
						message: '操作成功！'
					});
				} else {
					ElMessage.error({
						message: result.data.msg
					});
				}
				// //
				setTimeout(() => {
					openDialog();
					emits('update');
				}, 1);
			} else {
				//
				console.log('error submit!', fields);
			}
		});
	}
	defineExpose({
		openDialog
	});
</script>
<style>
	@import '../../../assets/css/my-form-item.css';

	.form-item-bg {
		background-color: #bfdfff;
	}

	.form-item-bg1 {
		background-color: #a5f2e5;
	}

	.my.el-input .el-input__inner {
		opacity: 0;
	}

	/*  */
	.avatar-uploader {
		width: 178px;
		height: 178px;
	}

	.avatar-uploader .avatar {
		width: 100%;
		height: 100%;
	}

	.avatar-uploader .el-upload {
		width: 100%;
		height: 100%;
		border: 1px dashed var(--el-border-color);
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
		transition: var(--el-transition-duration-fast);
	}

	.avatar-uploader .el-upload:hover {
		border-color: var(--el-color-primary);
	}

	.el-icon.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 178px;
		height: 178px;
		text-align: center;
	}

	.el-scrollbar__view {
		display: block !important;
	}

	/*  */
</style>

<style scoped lang="scss">
	@import '../../../assets/css/index.scss';
</style>